package com.xusheng.cli.controller.back;

import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.StrUtil;
import com.xusheng.cli.common.base.Attachment;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.enums.FileDirectoryEnum;
import com.xusheng.cli.common.exception.ServiceException;
import com.xusheng.cli.entity.videoModule.Video;
import com.xusheng.cli.req.VideoQueryReq;
import com.xusheng.cli.service.VideoService;
import com.xusheng.cli.tools.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 视频相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/video")
public class VideoController {

    @Resource
    private VideoService videoService;

    @Value("${serverIp}")
    private String serverIp;

    /**
     * 通过条件查询视频信息
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public Result<MyPage<Video>> list(VideoQueryReq req) {
        return Result.success(videoService.videoList(req));
    }

    /**
     * 保存视频信息
     *
     * @param video 视频信息
     * @return 返回结果
     */
    @PostMapping("/insert")
    public Result<Object> insert(@Validated Video video, @RequestParam("imgFile") MultipartFile img) {
        if (img == null || img.isEmpty()) {
            throw new ServiceException("缩略图不能为空");
        }
        Attachment attachment = FileUtils.uploadSingleFile(img, FileDirectoryEnum.RICHTEXTIMAGE);
        video.setImage(serverIp + attachment.getUrl());
        video.setImageFilename(attachment.getPath());
//        if (video.getActressId() == 0) {
//            video.setActressId(null);
//        }
        return Result.isSuccess(videoService.save(video));
    }

    @PostMapping("/save")
    public Result<Object> save(@Validated Video video, @RequestParam(name = "file", required = false) MultipartFile file,
                               @RequestParam("imgFile") MultipartFile img) {
        if (img == null || img.isEmpty()) {
            throw new ServiceException("缩略图不能为空");
        }
        checkVideo(video, file);
        Attachment attachment = FileUtils.uploadSingleFile(img, FileDirectoryEnum.RICHTEXTIMAGE);
        video.setImage(serverIp + attachment.getUrl());
        video.setImageFilename(attachment.getPath());
        return Result.isSuccess(videoService.save(video));
    }

    @PostMapping("/saveShortVideo")
    public Result<Object> saveShortVideo(@Validated Video video, @RequestParam(name = "file", required = false) MultipartFile file) {
        checkVideo(video, file);
        return Result.isSuccess(videoService.save(video));
    }

    /**
     * 批量上传
     *
     * @param video
     * @param file
     * @return
     */
    @PostMapping("/batchUpload")
    public Result<Object> batchUpload(@Validated Video video, @RequestParam(name = "file", required = false) List<MultipartFile> file) {
        log.info("文件：{}", file);
        video.setSource(0);
        List<Video> videoList = new ArrayList<>();
        for (MultipartFile f : file) {
            checkVideo(video, f);
            videoList.add(video);
        }
        log.info("videoList：{}", videoList);
        return Result.isSuccess(videoService.saveBatch(videoList));
    }

    /**
     * 更新视频信息
     *
     * @param video 视频信息
     * @return 返回结果
     */
    @PostMapping("/update")
    public Result<Object> update(@Validated Video video, @RequestParam(name = "file", required = false) MultipartFile file,
                                 @RequestParam(name = "imgFile", required = false) MultipartFile img) {
        if (file != null && !file.isEmpty()) {
            checkVideo(video, file);
        }
        if (img != null && !img.isEmpty()) {
            Attachment attachment = FileUtils.uploadSingleFile(img, FileDirectoryEnum.RICHTEXTIMAGE);
            video.setImage(serverIp + attachment.getUrl());
            video.setImageFilename(attachment.getPath());
        }
        if (video.getActressId() != null && video.getActressId() == 0) {
            video.setActressId(null);
        }
        return Result.isSuccess(videoService.updateById(video));
    }

    /**
     * 通过id获取视频信息
     *
     * @param id 视频编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public Result<Video> info(@PathVariable long id) {
        Video video = videoService.getById(id);
        return Result.success(video);
    }

    /**
     * 通过id删除视频信息
     *
     * @param id 视频编号
     * @return 返回结果
     */
    @DeleteMapping("/{id}")
    public Result<Object> delete(@PathVariable long id) {
        return Result.isSuccess(videoService.deleteVideo(id));
    }

    private void checkVideo(Video video, MultipartFile file) {
        if (video.getSource() == 0) {
            if (file == null) {
                throw new ServiceException("请上传文件");
            }
            Long categoryId = video.getCategoryId();
            if (categoryId == null) {
                categoryId = 0L;
            }
            Attachment attachment = FileUtils.uploadSingleFile(file, FileDirectoryEnum.ATTACHMENT.getDirectory() + File.separator + categoryId);
            video.setUrl(serverIp + attachment.getUrl());
            video.setFilename(attachment.getPath());
        } else {
            if (StrUtil.isBlank(video.getUrl())) {
                throw new ServiceException("请输入视频链接地址");
            }
            if (!video.getUrl().matches(RegexPool.URL)) {
                throw new ServiceException("视频地址格式错误");
            }
        }
    }
}
